//
//  YHOAuthViewController.swift
//  YHWeibo
//
//  Created by yuhao.mac on 16/6/25.
//  Copyright © 2016年 yuhao.mac. All rights reserved.
//

import UIKit
import SVProgressHUD


class YHOAuthViewController: UIViewController {
    
    override func loadView() {
        view = webView
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

    private func setupUI(){
//        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }
    
    func setupNav(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "cancelBtnClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFillClick")
        navigationItem.title = "OAuth登录"
    }
    
    @objc private func cancelBtnClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func autoFillClick(){
        let jsString =  "document.getElementById('userId').value='15116904135',document.getElementById('passwd').value='210008360569@'"
        //JS注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    private lazy var webView:UIWebView = {
    
        let view = UIWebView()
        view.delegate = self
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
        let request = NSURLRequest(URL: url!)
        view.loadRequest(request)
        
        return view
    }()
}

extension YHOAuthViewController:UIWebViewDelegate{
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    //将要加载request
    //返回ture代表继续加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString
        //判断urlString是否有值  而且他们的前缀是我们的回调页
        if let u = urlString where u.hasPrefix(REDIRECT_URI){
            //请求参数的键值对
            let query = request.URL?.query
            //可选值判断
            if let q = query{
                let code = q.substringFromIndex("code=".endIndex)
                loadUserAccount(code)
                //如果我们已经拿到了code就没有必要继续加载
                return false
            }
        }
        
        return true
    }
}

extension YHOAuthViewController{

    func loadUserAccount(code:String){
        
        YHNetworkTools.sharedTools.oauthLoadUserAccount(code, success: { (response) -> () in
            //判断请求回来的res是否有值
            guard let res = response as? [String:AnyObject] else{
                print("返回的数据不是一个字典")
                return
            }
            //字典转模型
            let userAccount = YHUserAccount(dict: res)
            self.loadUserInfo(userAccount)
            
            }) { (error) -> () in
                print(error)
        }
    }
    
    func loadUserInfo(userAccount: YHUserAccount){
        YHNetworkTools.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) -> () in
            guard let res = response as? [String: AnyObject] else {
                return
            }
            
            userAccount.avatar_large = res["avatar_large"] as? String
            userAccount.screen_name = res["screen_name"] as? String
            //通过归档保存数据
            YHUserAccountTools.sharedTools.saveUserAccount(userAccount)
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                //关闭指示器
                SVProgressHUD.dismiss()
                //发送通知告知appDelegate切换控制器
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVcNoti, object: nil)
            })
            
            }) { (error) -> () in
                print(error)
        }
    }
}





